<?php
class DataApp{
	private $Name;
	private $SecretKey;
	private $Directory = array();
	private $StaticKeys = array();
	private $UserKeys = array();
	function __construct(){
		$this->SecretKey = unpack('C*', UtilHash::generateKey( 32 )  ) ;
	}
	static function swap($bytebuffer){
		$obj = new DataApp();	
		$obj->Name = DataUtil::readBBin( $bytebuffer ) ;
		$obj->Directory = DataUtil::readBBin( $bytebuffer ) ;
		$obj->SecretKey = DataUtil::readBBin( $bytebuffer ) ;
		$num_of_static_keys = DataUtil::readInt32( $bytebuffer ) ;
		for($i = 0; $i< $num_of_static_keys; $i++){
			$obj->StaticKeys[] = DataUtil::readSBin( $bytebuffer ) ;
		}
		$num_of_user_keys = DataUtil::readInt32( $bytebuffer ) ;
		for($i = 0; $i < $num_of_user_keys; $i++){
			$obj->UserKeys[] = DataUtil::readSBin( $bytebuffer ) ;
		}
		return $obj;
	}
	function setName($name){
		$this->Name = unpack('C*', $name ) ;
	}
	function setDirectory($directory){
		$this->Directory = unpack('C*', $directory ) ;
	}
	function getDirectory(){
		return implode(array_map("chr",  $this->Directory )) ;
	}
	function getSecretKey(){
		return implode(array_map("chr",  $this->SecretKey )) ;
	}
	function addStaticKey($key){
		if(is_array($this->StaticKeys)){
			foreach($this->StaticKeys as $skey){
				if(implode(array_map("chr",  $skey ))  == $key) return;
			}
		}
		$this->StaticKeys[] = unpack('C*', $key ) ;
	}
	function addUserKey($key){
		if(is_array($this->UserKeys)){
			foreach($this->UserKeys as $skey){
				if(implode(array_map("chr",  $skey ))  == $key) return;
			}
		}
		$this->UserKeys[] = unpack('C*', $key ) ;
	}
	function getBinSize(){
		$size = 0;
		$size += 1  + count($this->Name);
		$size += 1  + count($this->Directory);
		$size += 1  + count($this->SecretKey);
		$size += 4 ;
		if(is_array($this->StaticKeys)){
			foreach($this->StaticKeys as $key){
				$size += 2  + count($key);
			}
		}
		$size += 4 ;
		if(is_array($this->UserKeys)){
			foreach($this->UserKeys as $key){
				$size += 2  + count($key);
			}
		}
		return $size;
	}
	function getBinary(){
		$buf = ByteBuffer::allocate( $this->getBinSize() ) ;
		DataUtil::writeBBin( $buf , $this->Name ) ;
		DataUtil::writeBBin( $buf , $this->Directory ) ;
		DataUtil::writeBBin( $buf , $this->SecretKey ) ;
		DataUtil::writeInt32( $buf , count($this->StaticKeys) ) ;
		if(is_array($this->StaticKeys)){
			foreach($this->StaticKeys as $key){
				DataUtil::writeSBin( $buf , $key ) ;
			}
		}
		DataUtil::writeInt32( $buf ,  count($this->UserKeys) ) ;
		if(is_array($this->UserKeys)){
			foreach($this->UserKeys as $key){
				DataUtil::writeSBin( $buf , $key ) ;
			}
		}
		return  $buf ->_array() ;
	}
}
?>